// DOM元素
const booksContainer = document.getElementById('books-container');
const emptyState = document.getElementById('empty-state');
const addBookBtn = document.getElementById('add-book-btn');
const bookModal = document.getElementById('book-modal');
const deleteModal = document.getElementById('delete-modal');
const closeModalBtn = document.getElementById('close-modal');
const closeDeleteModalBtn = document.getElementById('close-delete-modal');
const cancelBtn = document.getElementById('cancel-btn');
const cancelDeleteBtn = document.getElementById('cancel-delete-btn');
const bookForm = document.getElementById('book-form');
const modalTitle = document.getElementById('modal-title');
const bookIdInput = document.getElementById('book-id');
const confirmDeleteBtn = document.getElementById('confirm-delete-btn');
const bookToDeleteEl = document.querySelector('.book-to-delete');
const searchInput = document.getElementById('search-input');
const searchBtn = document.getElementById('search-btn');
const statusFilter = document.getElementById('status-filter');
const sortSelect = document.getElementById('sort-select');
const toast = document.getElementById('toast');

// 统计元素
const totalBooksEl = document.getElementById('total-books');
const readBooksEl = document.getElementById('read-books');
const readingBooksEl = document.getElementById('reading-books');
const wantReadBooksEl = document.getElementById('want-read-books');
const avgRatingEl = document.getElementById('avg-rating');

// 书籍数据存储键
const STORAGE_KEY = 'personalBookTracker_books';

// 当前编辑或删除的书籍ID
let currentBookId = null;

// 初始化应用
function initApp() {
    // 从本地存储加载书籍数据
    loadBooks();
    
    // 添加事件监听器
    addBookBtn.addEventListener('click', openAddBookModal);
    closeModalBtn.addEventListener('click', closeModal);
    closeDeleteModalBtn.addEventListener('click', closeDeleteModal);
    cancelBtn.addEventListener('click', closeModal);
    cancelDeleteBtn.addEventListener('click', closeDeleteModal);
    bookForm.addEventListener('submit', handleFormSubmit);
    confirmDeleteBtn.addEventListener('click', deleteBook);
    searchBtn.addEventListener('click', handleSearch);
    searchInput.addEventListener('keyup', (e) => {
        if (e.key === 'Enter') handleSearch();
    });
    statusFilter.addEventListener('change', filterBooks);
    sortSelect.addEventListener('change', sortBooks);
    
    // 点击模态框外部关闭模态框
    window.addEventListener('click', (e) => {
        if (e.target === bookModal) closeModal();
        if (e.target === deleteModal) closeDeleteModal();
    });
    
    // 阻止表单提交的默认行为
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', (e) => e.preventDefault());
    });
}

// 从本地存储加载书籍
function loadBooks() {
    const books = getBooksFromStorage();
    renderBooks(books);
    updateStats(books);
    checkEmptyState(books.length > 0);
}

// 从本地存储获取书籍数据
function getBooksFromStorage() {
    try {
        const booksJson = localStorage.getItem(STORAGE_KEY);
        return booksJson ? JSON.parse(booksJson) : [];
    } catch (error) {
        console.error('Error loading books from storage:', error);
        return [];
    }
}

// 保存书籍数据到本地存储
function saveBooksToStorage(books) {
    try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(books));
        return true;
    } catch (error) {
        console.error('Error saving books to storage:', error);
        showToast('数据保存失败，请检查存储空间', 'error');
        return false;
    }
}

// 渲染书籍列表
function renderBooks(books) {
    booksContainer.innerHTML = '';
    
    books.forEach(book => {
        const bookCard = createBookCard(book);
        booksContainer.appendChild(bookCard);
    });
    
    checkEmptyState(books.length > 0);
}

// 创建书籍卡片
function createBookCard(book) {
    const card = document.createElement('div');
    card.className = 'book-card';
    
    // 根据阅读状态设置不同的样式类
    let statusClass = '';
    switch (book.status) {
        case '想读': statusClass = 'status-want-read'; break;
        case '在读': statusClass = 'status-reading'; break;
        case '已读': statusClass = 'status-read'; break;
    }
    
    // 创建星级评分显示
    const ratingHtml = book.rating ? '⭐'.repeat(parseInt(book.rating)) : '未评分';
    
    // 设置卡片内容
    card.innerHTML = `
        <div class="book-status ${statusClass}">${book.status}</div>
        <h3 class="book-title">${book.title}</h3>
        <p class="book-author">${book.author}</p>
        <div class="book-info">
            ${book.pages ? `页数: ${book.pages}` : ''}
        </div>
        <div class="book-rating">${ratingHtml}</div>
        ${book.review ? `<p class="book-review">${book.review}</p>` : ''}
        <div class="book-actions">
            <button class="edit-btn" data-id="${book.id}">编辑</button>
            <button class="remove-btn" data-id="${book.id}">删除</button>
        </div>
    `;
    
    // 添加编辑和删除按钮的事件监听器
    card.querySelector('.edit-btn').addEventListener('click', () => openEditBookModal(book));
    card.querySelector('.remove-btn').addEventListener('click', () => openDeleteBookModal(book));
    
    return card;
}

// 检查并显示空状态
function checkEmptyState(hasBooks) {
    if (hasBooks) {
        emptyState.style.display = 'none';
    } else {
        emptyState.style.display = 'block';
    }
}

// 更新统计信息
function updateStats(books) {
    const totalBooks = books.length;
    const readBooks = books.filter(book => book.status === '已读').length;
    const readingBooks = books.filter(book => book.status === '在读').length;
    const wantReadBooks = books.filter(book => book.status === '想读').length;
    
    // 计算平均评分
    const ratedBooks = books.filter(book => book.rating);
    const avgRating = ratedBooks.length > 0 
        ? (ratedBooks.reduce((sum, book) => sum + parseInt(book.rating), 0) / ratedBooks.length).toFixed(1)
        : '0.0';
    
    // 更新DOM元素
    totalBooksEl.textContent = totalBooks;
    readBooksEl.textContent = readBooks;
    readingBooksEl.textContent = readingBooks;
    wantReadBooksEl.textContent = wantReadBooks;
    avgRatingEl.textContent = avgRating;
}

// 打开添加书籍模态框
function openAddBookModal() {
    currentBookId = null;
    modalTitle.textContent = '添加新书籍';
    resetForm();
    openModal();
}

// 打开编辑书籍模态框
function openEditBookModal(book) {
    currentBookId = book.id;
    modalTitle.textContent = '编辑书籍';
    
    // 填充表单
    bookIdInput.value = book.id;
    document.getElementById('book-title').value = book.title;
    document.getElementById('book-author').value = book.author;
    document.getElementById('book-pages').value = book.pages || '';
    document.getElementById('book-status').value = book.status;
    document.getElementById('book-rating').value = book.rating || '';
    document.getElementById('book-review').value = book.review || '';
    
    openModal();
}

// 打开删除书籍模态框
function openDeleteBookModal(book) {
    currentBookId = book.id;
    bookToDeleteEl.textContent = book.title;
    deleteModal.style.display = 'block';
}

// 打开模态框
function openModal() {
    bookModal.style.display = 'block';
    // 自动聚焦到第一个输入框
    document.getElementById('book-title').focus();
}

// 关闭模态框
function closeModal() {
    bookModal.style.display = 'none';
    resetForm();
}

// 关闭删除模态框
function closeDeleteModal() {
    deleteModal.style.display = 'none';
    currentBookId = null;
}

// 重置表单
function resetForm() {
    bookForm.reset();
    bookIdInput.value = '';
    currentBookId = null;
}

// 处理表单提交
function handleFormSubmit(e) {
    e.preventDefault();
    
    // 获取表单数据
    const bookData = {
        title: document.getElementById('book-title').value.trim(),
        author: document.getElementById('book-author').value.trim(),
        pages: document.getElementById('book-pages').value || '',
        status: document.getElementById('book-status').value,
        rating: document.getElementById('book-rating').value || '',
        review: document.getElementById('book-review').value.trim()
    };
    
    // 表单验证
    if (!bookData.title || !bookData.author) {
        showToast('请填写书名和作者', 'error');
        return;
    }
    
    // 如果是编辑模式，获取现有书籍列表
    const books = getBooksFromStorage();
    
    if (currentBookId) {
        // 更新现有书籍
        const index = books.findIndex(book => book.id === currentBookId);
        if (index !== -1) {
            books[index] = { ...books[index], ...bookData };
            if (saveBooksToStorage(books)) {
                showToast('书籍已更新');
                filterBooks();
                closeModal();
            }
        }
    } else {
        // 添加新书籍
        const newBook = {
            ...bookData,
            id: generateUniqueId()
        };
        
        books.push(newBook);
        if (saveBooksToStorage(books)) {
            showToast('书籍已添加');
            filterBooks();
            closeModal();
        }
    }
}

// 删除书籍
function deleteBook() {
    if (!currentBookId) return;
    
    const books = getBooksFromStorage();
    const filteredBooks = books.filter(book => book.id !== currentBookId);
    
    if (saveBooksToStorage(filteredBooks)) {
        showToast('书籍已删除');
        filterBooks();
        closeDeleteModal();
    }
}

// 生成唯一ID
function generateUniqueId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2, 9);
}

// 处理搜索
function handleSearch() {
    filterBooks();
}

// 过滤书籍
function filterBooks() {
    const books = getBooksFromStorage();
    const searchTerm = searchInput.value.toLowerCase().trim();
    const statusValue = statusFilter.value;
    
    let filteredBooks = books;
    
    // 应用搜索过滤
    if (searchTerm) {
        filteredBooks = filteredBooks.filter(book => 
            book.title.toLowerCase().includes(searchTerm) || 
            book.author.toLowerCase().includes(searchTerm)
        );
    }
    
    // 应用状态过滤
    if (statusValue !== 'all') {
        filteredBooks = filteredBooks.filter(book => book.status === statusValue);
    }
    
    // 应用排序
    sortBooks(filteredBooks);
}

// 排序书籍
function sortBooks(books = null) {
    // 如果没有传入书籍列表，则获取当前过滤后的列表
    let booksToSort = books;
    if (!booksToSort) {
        booksToSort = getBooksFromStorage();
        const searchTerm = searchInput.value.toLowerCase().trim();
        const statusValue = statusFilter.value;
        
        // 应用搜索过滤
        if (searchTerm) {
            booksToSort = booksToSort.filter(book => 
                book.title.toLowerCase().includes(searchTerm) || 
                book.author.toLowerCase().includes(searchTerm)
            );
        }
        
        // 应用状态过滤
        if (statusValue !== 'all') {
            booksToSort = booksToSort.filter(book => book.status === statusValue);
        }
    }
    
    // 获取排序方式
    const sortMethod = sortSelect.value;
    
    // 应用排序
    const sortedBooks = [...booksToSort].sort((a, b) => {
        switch (sortMethod) {
            case 'title-asc':
                return a.title.localeCompare(b.title);
            case 'title-desc':
                return b.title.localeCompare(a.title);
            case 'author-asc':
                return a.author.localeCompare(b.author);
            case 'author-desc':
                return b.author.localeCompare(a.author);
            case 'rating-desc':
                return (parseInt(b.rating) || 0) - (parseInt(a.rating) || 0);
            case 'rating-asc':
                return (parseInt(a.rating) || 0) - (parseInt(b.rating) || 0);
            default:
                return 0;
        }
    });
    
    // 渲染排序后的书籍列表
    renderBooks(sortedBooks);
    updateStats(sortedBooks); // 更新显示的统计信息
}

// 显示提示消息
function showToast(message, type = 'success') {
    toast.textContent = message;
    toast.className = 'toast'; // 重置类名
    
    // 添加类型类
    if (type === 'error') {
        toast.classList.add('error');
    } else if (type === 'info') {
        toast.classList.add('info');
    }
    
    // 显示提示
    toast.classList.add('show');
    
    // 3秒后自动隐藏
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 页面加载完成后初始化应用
window.addEventListener('DOMContentLoaded', initApp);